package com.valdemar.demos;

import java.util.Date;

import com.google.android.c2dm.C2DMessaging;
import com.valdemar.android.givemeanswers.shared.GiveMeAnswersRequestFactory;
import com.valdemar.android.givemeanswers.shared.QuestionProxy;
import com.valdemar.android.givemeanswers.shared.QuestionsRequest;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class AuthTokenActivity extends Activity
{
	TextView authToken;
	private static final int ACCOUNTS_ACTIVITY_RESULT_CODE = 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		authToken = (TextView) findViewById(R.id.token);
	}

	public void onGoToAccountClick(View view)
	{
		startActivityForResult(new Intent(this, AccountsActivity.class), ACCOUNTS_ACTIVITY_RESULT_CODE);
	}

	public void onRegisterC2DMClick(View view)
	{
		C2DMessaging.register(this, Setup.SENDER_ID);
	}

	public void onFetchQuestionClick(View view)
	{
		new AsyncFetchDemo(this).execute(-1l);
		
	}

	public void onAddQuestionsClick(View view)
	{

		new AsyncTask<Void, Void, Void>()
		{

			@Override
			protected Void doInBackground(Void... arg0)
			{
				Date d = new Date();
				GiveMeAnswersRequestFactory factory = (GiveMeAnswersRequestFactory) Util
						.getRequestFactory(getBaseContext(),
								GiveMeAnswersRequestFactory.class);
				QuestionsRequest request = factory.questionRequest();

				QuestionProxy question = request.create(QuestionProxy.class);
				question.setName("name: " + d.getTime());
				question.setNote("Some Details");

				request.updateQuestion(question).fire();

				return null;
			}

		}.execute();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode)
		{
			case ACCOUNTS_ACTIVITY_RESULT_CODE:
				if (resultCode == RESULT_OK)
				{
					SharedPreferences prefs = Util.getSharedPreferences(this);
					authToken.setText("Token: " + prefs.getString(Util.AUTH_COOKIE, ""));
				}
				else
					authToken.setText("error...");
				break;

			default:
				break;
		}
	}
}